import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Modal, Select, TreeSelect, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type {
  AddTenantRoleBean,
  RoleItem,
  UpdateRoleNameBean,
  UpdateRolePermissionBean,
} from './data';
import {
  updateRoleName,
  addTenantRole,
  pageQueryRole,
  updateRolePermission,
  deleteAuthPermissionV2,
} from './service';
import { queryDepartment } from '@/pages/user/Department/service';
import { queryPositionByDep } from '@/pages/user/Admin/service';
import AddForm from './components/AddForm';
import EditForm from './components/EditForm';
import { SUCCESS_CODE } from '@/utils/request';
import AuthPermissionConfiguration from './components/AuthPermissionConfiguration';
import { useModel } from 'umi';

const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const {
    'ROLE.ADD.TENANT': add,
    'ROLE.UPDATE': update,
    'ROLE.DELETE.TENANT': Delete,
    'ROLE.VIEW': view,
    'ROLE.TEMPLATE.VIEW': template,
    'ROLE.PERMISSION.VIEW': permissionView,
    'ROLE.PERMISSION.UPDATE': permissionUpdate,
  } = currUser;
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [editPermissionVisible, setEditPermissionVisible] = useState<boolean>(false);
  const [editVisible, setEditVisible] = useState<boolean>(false);
  const [roleData, setRoleData] = useState<RoleItem>();
  const actionRef = useRef<ActionType>();

  const [treeDate, setTreeDate] = useState<any[]>([]);
  const [positionData, setPositionData] = useState<any[]>();
  const [twoTreeDisplay, setTwoTreeDisplay] = useState(true);

  function convertData(data: { id: any; name: any; next_level: string | any[] }) {
    const node = {
      value: data.id,
      title: data.name,
      children: [] as any,
    };
    if (data.next_level && data.next_level.length > 0) {
      for (let i = 0; i < data.next_level.length; i++) {
        const child = convertData(data.next_level[i]);
        node.children.push(child);
      }
    }
    return node;
  }

  useEffect(() => {
    queryDepartment().then((res) => {
      if (res && res.code == 0) {
        const data = res?.data;
        const convert = [];
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            convert.push(convertData(data[i]));
          }
          setTreeDate(convert);
        }
      }
    });
  }, []);

  const handleAddEvent = async (values: AddTenantRoleBean) => {
    const hide = message.loading('正在添加');
    try {
      const res = await addTenantRole(values);
      hide();
      if (res.code == 0) {
        message.success('添加成功');
        actionRef.current?.reload();
        handleAddModalVisible(false);
      } else {
        message.error(`${res.message}`);
      }
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      handleAddModalVisible(false);
    }
  };

  const handleEditEvent = async (values: UpdateRoleNameBean) => {
    const res = await updateRoleName(values);
    if (res.code === SUCCESS_CODE) {
      setEditVisible(false);
      message.success('修改成功');
      actionRef.current?.reload();
    } else {
      message.error(res.message || '修改失败');
    }
  };

  const handleEditPermissionEvent = async (values: UpdateRolePermissionBean) => {
    const res = await updateRolePermission(values);
    if (res.code === SUCCESS_CODE) {
      setEditPermissionVisible(false);
      message.success('修改成功');
    } else {
      message.error(res.message || '修改失败');
    }
  };

  const columns: ProColumns<RoleItem>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
    },
    {
      title: '部门',
      dataIndex: 'department_id',
      key: 'department_id',
      hideInTable: true,
      renderFormItem: () => (
        <TreeSelect
          showSearch
          style={{ width: '100%' }}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          placeholder="请选择部门"
          allowClear
          autoClearSearchValue
          treeDefaultExpandAll
          onChange={(newValue, _labelList) => {
            if (newValue) {
              queryPositionByDep(newValue).then((res) => {
                if (res && res.code == 0) {
                  const data = res?.data;
                  const convert = [];
                  if (data && data.length > 0) {
                    for (let i = 0; i < data.length; i++) {
                      convert.push(convertData(data[i]));
                    }
                    setPositionData(convert);
                    setTwoTreeDisplay(false);
                  }
                }
              });
            }
          }}
          treeData={treeDate}
        />
      ),
    },
    {
      title: '职位',
      dataIndex: 'position_id',
      key: 'position_id',
      hideInTable: true,
      renderFormItem: () => (
        <TreeSelect
          disabled={twoTreeDisplay}
          autoClearSearchValue
          showSearch
          style={{ width: '100%' }}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          placeholder="请选择职位"
          allowClear
          treeDefaultExpandAll
          treeData={positionData}
        />
      ),
    },
    {
      title: '层级',
      dataIndex: 'level_code',
      key: 'level_code',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <TreeSelect
            autoClearSearchValue
            showSearch
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择层级"
            allowClear
            treeDefaultExpandAll
            getPopupContainer={(triggerNode) => triggerNode.parentElement} // 保证选择菜单不会随着页面滚动
            treeData={[
              {
                key: '10',
                value: '10',
                title: '市场部管理员',
                children: [
                  {
                    key: '11',
                    value: '11',
                    title: '销售总经理',
                    children: [
                      {
                        key: '12',
                        value: '12',
                        title: '大区总监',
                        children: [{ key: '13', value: '13', title: '销售人员' }],
                      },
                    ],
                  },
                ],
              },
              {
                key: '20',
                value: '20',
                title: '项目部管理员',
                children: [
                  {
                    key: '21',
                    value: '21',
                    title: '项目组管理员',
                    children: [{ key: '22', value: '22', title: '组员' }],
                  },
                ],
              },
              { key: '30', value: '30', title: '客户' },
            ]}
          />
        );
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <Select
            options={[
              { key: '0', value: '0', label: '全部' },
              { key: '1', value: '1', label: '管理员角色' },
              { key: '2', value: '2', label: '客户角色' },
              { key: '3', value: '3', label: '角色模板' },
            ]}
          />
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'options',
      key: 'options',
      hideInSearch: true,
      ellipsis: true,
      render: (_, record) => {
        const onClickDetail = () => {
          setEditPermissionVisible(true);
          setRoleData(record);
        };
        const onClickRemove = () => {
          const { name, id } = record;
          Modal.confirm({
            title: `确定要删除 ${name} 吗？`,
            content: (
              <>
                <p>删除之后无法撤回，请谨慎操作！</p>
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await deleteAuthPermissionV2({ id });
              actionRef.current?.reload();
            },
            centered: true,
            style: { height: '15vw' },
          });
        };
        return (
          <div>
            {update && <a onClick={onClickDetail}>修改权限</a>}
            {update && (
              <>
                <Divider type="vertical" />
                <a
                  onClick={() => {
                    setEditVisible(true);
                    setRoleData(record);
                  }}
                >
                  修改名称
                </a>
              </>
            )}
            {Delete && (
              <>
                <Divider type="vertical" /> <a onClick={onClickRemove}>删除</a>
              </>
            )}
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<RoleItem>
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        headerTitle="角色列表"
        actionRef={actionRef}
        scroll={{ x: true }}
        toolBarRender={() => [
          <>
            {add && (
              <Button type="primary" onClick={() => handleAddModalVisible(true)}>
                <PlusOutlined /> 添加客户角色
              </Button>
            )}
          </>,
        ]}
        request={async (params) => {
          params.page = params.current;
          return pageQueryRole(params);
        }}
        columns={columns}
      />

      {addModalVisible && (
        <AddForm
          modalVisible={addModalVisible}
          visibleHandler={() => handleAddModalVisible(false)}
          onCancel={() => handleAddModalVisible(false)}
          onSubmit={handleAddEvent}
        />
      )}
      {editVisible && roleData && (
        <EditForm
          role={roleData}
          onSubmit={handleEditEvent}
          modalVisible={editVisible}
          visibleHandler={() => setEditVisible(false)}
          onCancel={() => setEditVisible(false)}
        />
      )}
      {editPermissionVisible && roleData && (
        <AuthPermissionConfiguration
          id={roleData.id}
          visible={editPermissionVisible}
          onCancel={() => setEditPermissionVisible(false)}
          onChange={handleEditPermissionEvent}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default TableList;
